<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="部门名称" prop="deptName">
        <el-input
            v-model="queryParams.deptName"
            placeholder="请输入部门名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable style="width: 200px">
          <el-option
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:dept:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="CopyDocument"
            @click="handleAddPeer(null)"
            v-hasPermi="['system:dept:add']"
        >添加同级组织</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Sort"
            @click="toggleExpandAll"
        >{{ isExpandAll ? '全部收起' : '全部展开' }}</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 组织架构图 - 卡片形式 -->
    <div class="org-chart-horizontal" v-loading="loading">
      <div v-if="!loading && deptList.length > 0" class="org-container">
        <!-- 公司节点 - 卡片 -->
        <div class="company-level" v-if="rootDept">
          <div class="card-node company-node" @click="handleNodeClick(rootDept)">
            <div class="node-header">
              <div class="node-icon company-icon">
                <i class="el-icon-office-building"></i>
              </div>
              <div class="node-title">{{ rootDept.deptName }}</div>
              <div class="node-actions">
                <el-button link type="primary" icon="Edit" @click.stop="handleUpdate(rootDept)" v-hasPermi="['system:dept:edit']"></el-button>
                <el-button link type="primary" icon="Plus" @click.stop="handleAdd(rootDept)" v-hasPermi="['system:dept:add']"></el-button>
                <el-button link type="primary" icon="CopyDocument" @click.stop="handleAddPeer(rootDept)" v-hasPermi="['system:dept:add']"></el-button>
                <el-button
                    v-if="rootDept.children && rootDept.children.length > 0"
                    link
                    type="primary"
                    :icon="rootDept.expanded ? 'ArrowDown' : 'ArrowRight'"
                    @click.stop="toggleDept(rootDept)"
                    class="expand-btn"
                ></el-button>
              </div>
            </div>

            <!-- 子节点列表 -->
            <div v-if="rootDept.expanded && rootDept.children && rootDept.children.length > 0" class="children-list">
              <div
                  v-for="dept in rootDept.children"
                  :key="dept.deptId"
                  class="card-node dept-node"
                  @click="handleNodeClick(dept)"
              >
                <div class="node-header">
                  <div class="node-icon dept-icon">
                    <i class="el-icon-office-building"></i>
                  </div>
                  <div class="node-title">{{ dept.deptName }}</div>
                  <div class="node-actions">
                    <el-button link type="primary" icon="Edit" @click.stop="handleUpdate(dept)" v-hasPermi="['system:dept:edit']"></el-button>
                    <el-button link type="primary" icon="Plus" @click.stop="handleAdd(dept)" v-hasPermi="['system:dept:add']"></el-button>
                    <el-button link type="primary" icon="CopyDocument" @click.stop="handleAddPeer(dept)" v-hasPermi="['system:dept:add']"></el-button>
                    <el-button
                        v-if="dept.parentId != 0"
                        link
                        type="primary"
                        icon="Delete"
                        @click.stop="handleDelete(dept)"
                        v-hasPermi="['system:dept:remove']"
                    ></el-button>
                    <el-button
                        v-if="dept.children && dept.children.length > 0"
                        link
                        type="primary"
                        :icon="dept.expanded ? 'ArrowDown' : 'ArrowRight'"
                        @click.stop="toggleDept(dept)"
                        class="expand-btn"
                    ></el-button>
                  </div>
                </div>

                <!-- 子子节点列表 -->
                <div v-if="dept.expanded && dept.children && dept.children.length > 0" class="children-list">
                  <div
                      v-for="team in dept.children"
                      :key="team.deptId"
                      class="card-node team-node"
                      @click="handleNodeClick(team)"
                  >
                    <div class="node-header">
                      <div class="node-icon team-icon">
                        <i class="el-icon-user"></i>
                      </div>
                      <div class="node-title">{{ team.deptName }}</div>
                      <div class="node-actions">
                        <el-button link type="primary" icon="Edit" @click.stop="handleUpdate(team)" v-hasPermi="['system:dept:edit']"></el-button>
                        <el-button link type="primary" icon="Plus" @click.stop="handleAdd(team)" v-hasPermi="['system:dept:add']"></el-button>
                        <el-button link type="primary" icon="CopyDocument" @click.stop="handleAddPeer(team)" v-hasPermi="['system:dept:add']"></el-button>
                        <el-button
                            link
                            type="primary"
                            icon="Delete"
                            @click.stop="handleDelete(team)"
                            v-hasPermi="['system:dept:remove']"
                        ></el-button>
                        <el-button
                            v-if="team.children && team.children.length > 0"
                            link
                            type="primary"
                            :icon="team.expanded ? 'ArrowDown' : 'ArrowRight'"
                            @click.stop="toggleDept(team)"
                            class="expand-btn"
                        ></el-button>
                      </div>
                    </div>

                    <!-- 子子子节点列表 -->
                    <div v-if="team.expanded && team.children && team.children.length > 0" class="children-list">
                      <div
                          v-for="group in team.children"
                          :key="group.deptId"
                          class="card-node group-node"
                          @click="handleNodeClick(group)"
                      >
                        <div class="node-header">
                          <div class="node-icon group-icon">
                            <i class="el-icon-user-solid"></i>
                          </div>
                          <div class="node-title">{{ group.deptName }}</div>
                          <div class="node-actions">
                            <el-button link type="primary" icon="Edit" @click.stop="handleUpdate(group)" v-hasPermi="['system:dept:edit']"></el-button>
                            <el-button link type="primary" icon="Plus" @click.stop="handleAdd(group)" v-hasPermi="['system:dept:add']"></el-button>
                            <el-button link type="primary" icon="CopyDocument" @click.stop="handleAddPeer(group)" v-hasPermi="['system:dept:add']"></el-button>
                            <el-button
                                link
                                type="primary"
                                icon="Delete"
                                @click.stop="handleDelete(group)"
                                v-hasPermi="['system:dept:remove']"
                            ></el-button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else-if="!loading" class="empty-container">
        <el-empty description="暂无部门数据">
          <el-button type="primary" @click="handleAdd">新增部门</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>


<script setup name="Dept">
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept"
import { ref, reactive, getCurrentInstance, nextTick, toRefs, computed } from 'vue'

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")

const deptList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const deptOptions = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)

const data = reactive({
  form: {},
  queryParams: {
    deptName: undefined,
    status: undefined
  },
  rules: {
    parentId: [{ required: true, message: "上级部门不能为空", trigger: "blur" }],
    deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
    orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  },
})

const { queryParams, form, rules } = toRefs(data)

// 计算属性
const rootDept = computed(() => {
  const root = deptList.value.find(dept => dept.parentId === 0) || deptList.value[0]
  if (root && !root.hasOwnProperty('expanded')) {
    root.expanded = isExpandAll.value
  }
  return root
})

/** 查询部门列表 */
function getList() {
  loading.value = true
  listDept(queryParams.value).then(response => {
    deptList.value = proxy.handleTree(response.data, "deptId")

    // 为所有部门添加展开状态
    const addExpandState = (depts, expanded) => {
      depts.forEach(dept => {
        dept.expanded = expanded
        if (dept.children && dept.children.length > 0) {
          addExpandState(dept.children, expanded)
        }
      })
    }

    addExpandState(deptList.value, isExpandAll.value)

    loading.value = false
  }).catch(error => {
    console.error('获取部门数据失败:', error)
    loading.value = false
  })
}

/** 获取状态文本 */
function getStatusText(status) {
  const dict = sys_normal_disable.value.find(item => item.value === status)
  return dict ? dict.label : '未知'
}

/** 节点点击事件 */
function handleNodeClick(data) {
  console.log('点击部门:', data.deptName)
  proxy.$modal.msgSuccess(`点击了: ${data.deptName}`)
}

/** 切换部门展开状态 */
function toggleDept(dept) {
  dept.expanded = !dept.expanded
  console.log('切换部门展开状态:', dept.deptName, dept.expanded)
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "0"
  }
  proxy.resetForm("deptRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId")
  })
  if (row != undefined) {
    form.value.parentId = row.deptId
  }
  open.value = true
  title.value = "添加下级组织"
}

/** 添加同级组织 */
function handleAddPeer(row) {
  reset()
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId")
  })

  if (row) {
    // 如果有传入部门，则设置与传入部门相同的父级
    form.value.parentId = row.parentId
    // 获取当前部门的父级部门信息，用于显示
    const parentDept = findDeptById(deptList.value, row.parentId)
    if (parentDept) {
      title.value = `在【${parentDept.deptName}】下添加同级组织`
    } else {
      title.value = "添加同级组织"
    }
  } else {
    // 如果没有传入部门，则添加顶级组织（与公司同级）
    form.value.parentId = 0
    title.value = "添加顶级组织"
  }

  open.value = true
}

/** 根据ID查找部门 */
function findDeptById(depts, deptId) {
  for (const dept of depts) {
    if (dept.deptId === deptId) {
      return dept
    }
    if (dept.children && dept.children.length > 0) {
      const found = findDeptById(dept.children, deptId)
      if (found) return found
    }
  }
  return null
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  isExpandAll.value = !isExpandAll.value

  // 递归设置所有节点的展开状态
  const setNodeExpand = (depts, expanded) => {
    depts.forEach(dept => {
      dept.expanded = expanded
      if (dept.children && dept.children.length > 0) {
        setNodeExpand(dept.children, expanded)
      }
    })
  }

  setNodeExpand(deptList.value, isExpandAll.value)
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  listDeptExcludeChild(row.deptId).then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId")
  })
  getDept(row.deptId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改组织信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDept(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?').then(function() {
    return delDept(row.deptId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.org-chart-container {
  min-height: 600px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 卡片样式 */
.card-node {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-node:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.card-node.company-node {
  padding: 16px;
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.card-node.dept-node {
  padding: 12px;
  border-color: #11998e;
  box-shadow: 0 4px 12px rgba(17, 153, 142, 0.1);
}

.card-node.team-node {
  padding: 10px;
  border-color: #ff9a9e;
  box-shadow: 0 4px 12px rgba(255, 154, 158, 0.1);
}

.card-node.group-node {
  padding: 8px;
  border-color: #a8c0ff;
  box-shadow: 0 4px 12px rgba(168, 192, 255, 0.1);
}

/* 节点头部样式 */
.node-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border-bottom: 1px solid #eee;
}

.node-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #667eea;
  border-radius: 50%;
  background: #f0f4ff;
}

.card-node.company-node .node-icon {
  color: #667eea;
  background: #f0f4ff;
}

.card-node.dept-node .node-icon {
  color: #11998e;
  background: #e6f7f2;
}

.card-node.team-node .node-icon {
  color: #ff9a9e;
  background: #fff0f0;
}

.card-node.group-node .node-icon {
  color: #a8c0ff;
  background: #f0f5ff;
}

.node-title {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
  margin: 0;
}

.node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.card-node:hover .node-actions {
  opacity: 1;
}

/* 子节点列表样式 */
.children-list {
  padding: 8px 12px;
  margin-top: 8px;
  border-left: 2px solid #e4e7ed;
  background: #f8f9fa;
}

.children-list .card-node {
  margin: 0;
  padding: 8px 12px;
}
</style>
